package org.crmsystem.controller;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.crmsystem.model.Permission;
import org.crmsystem.model.Result;
import org.crmsystem.model.User;
import org.crmsystem.service.IPermissionService;
import org.crmsystem.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 用户控制层
 * 
 * @author 孙艳平
 */
@Controller
@RequestMapping
public class UserLoginController {
	@Autowired
    private IUserService iUserService;
	private IPermissionService iPermissionService;
	private static Logger logger=LogManager.getLogger(UserLoginController.class);
	/**
	 * 用户登录
	 * @param userName
	 * @param password
	 * @param rememberMe
	 * @param model
	 * @return
	 */
	@RequestMapping(value="toLogin",method={RequestMethod.POST,RequestMethod.GET})
	public String userLogin(@RequestParam("userName")String userName,@RequestParam("password")String password,
			@RequestParam(value="rememberMe",required=false)Boolean rememberMe,Model model){
		Subject subject=SecurityUtils.getSubject();
		UsernamePasswordToken token=new UsernamePasswordToken(userName,password);
		if(rememberMe!=null){
			token.setRememberMe(rememberMe);
		}
		try {
			subject.login(token);
		}catch (UnknownAccountException uae) {
			logger.info("未知账户");
		} catch (IncorrectCredentialsException ice) {
			logger.info("密码不正确");
		} catch (LockedAccountException lae) {
			logger.info("账户已锁定");
		} catch (ExcessiveAttemptsException eae) {
			logger.info("用户名密码次数过多");
		} catch(Exception ex){
			//logger.info("未知的异常");
			ex.printStackTrace();
		}
		if (subject.isAuthenticated()) {
			User user=(User) subject.getPrincipal();
			logger.debug(user);
			model.addAttribute("user", user);
			return "index";
		} else {
			return "redirect:/login.html";
		}
	}
	/**
	 * 获取用户的菜单
	 * @param userId
	 * @return
	 */
	@RequestMapping("/getMenus")
	@ResponseBody
	public Result<?> getUserMenus(Integer userId){
		List<Permission> permissionList=null;
		try {
			User user=iUserService.getUserById(userId);
			int roleId=user.getRoleId();
			permissionList=iPermissionService.getPermissionByRoleId(roleId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Result<List<Permission>> rd=new Result<List<Permission>>();
		rd.setCode(0);
		rd.setMessage("查询成功！");
		rd.setData(permissionList);
		logger.debug(rd);
		return rd;

	}
	@RequestMapping("/toIndex")
	public String toMain(){
		return "main";
	}
	
	/**
	 * 没有权限跳转到拒绝访问页面
	 * @return
	 */
	@RequestMapping(value="/index")
	private String toIndex(){
		return "index";
	}
	
	/**
	 * 没有权限跳转到拒绝访问页面
	 * @return
	 */
	@RequestMapping(value="/refuse")
	private String toRefuse(){
		return "forward:/refuse.html";
	}
	
	/**
	 * 注销登陆
	 * 
	 * @return
	 */    
	@RequestMapping("/logout")
	public String logout() {
		SecurityUtils.getSubject().logout();
		return "redirect:login";
	}
}
